#coding:utf8
#import web
import sys
import StringIO
import json
import fetchdata
import cPickle
import train_svc
import numpy as np
#import show
import tranpoint

class ContextHost(object):
    class Context(object):
        def __init__(self,data):
            self.data=data
        def maxbuy(self):
            return self.host.blance/self.data[-1]["Close"] - 0.0001
        def buy(self,amont,stoploss,stopearn):
            if self.host.blance>=self.data[-1]["Close"]*amont:
                self.host.litera.append({
                    "time":self.data[-1]["Date"],
                    "type":1,
                    "prise":self.data[-1]["Close"],
                    "amont":amont,
                    "range":[stoploss,stopearn]
                })
                mkprice=self.data[-1]["Close"]*amont
                self.host.blance-=mkprice
        def litera(self):
            return self.host.litera
    def __init__(self,data,blance=10000):
        self.calcgap=5
        self.data=data
        self.litera=[]
        self.closelitera=[]
        self.marketvalue=[]
        self.blance=blance
    def doLoop(self,fun):
        for i in xrange(self.calcgap,len(self.data)):
            dline=self.data[i]
            for j in self.litera[:]:
                if j["range"][0]>dline["Low"] :
                    j["close_prise"]=j["range"][0]
                    j["close_time"]=dline["Date"]
                    self.blance+=j["close_prise"]*j["amont"]
                    self.closelitera.append(j)
                    self.litera.remove(j)
                elif j["range"][1]<dline["High"]:
                    j["close_prise"]=j["range"][1]
                    j["close_time"]=dline["Date"]
                    self.blance+=j["close_prise"]*j["amont"]
                    self.closelitera.append(j)
                    self.litera.remove(j)
            now_mp=0
            for j in self.litera:
                if j["type"]==1:
                    now_mp+=dline['Close']*j["amont"]
            self.marketvalue.append(now_mp+self.blance)
            dline["mv"]=now_mp+self.blance
            ctx=ContextHost.Context(self.data[i-self.calcgap:i])
            ctx.host=self
            fun(ctx)
with open("/root/data/goldDI.svc", 'rb') as fid:
    svc=cPickle.load(fid)

def run(context):
    dline=train_svc.getone(context.data[-1])
    line=np.array([dline,])
    sres=svc.decision_function(line)
    context.data[-1]["svc"]=sres[0]
    allweight=0
    allsumsvc=0
    for i in xrange(len(context.data)):
        allweight+=i+1
        if "svc" not in context.data[i]:
            break
        allsumsvc+=context.data[i]["svc"]*(i+1)
    if allweight==0:
        return
    wsvc=allsumsvc/allweight
    print "In simulation, wsvc is:", wsvc
    context.data[-1]["wsvc"]=wsvc
    if "wsvc" in context.data[-2]:
        if wsvc>5 and context.data[-2]["wsvc"]>wsvc:
            context.buy(min(context.maxbuy(),5),context.data[-1]["Close"]-10,context.data[-1]["Close"]+40)

def getv(one,key):
    if key in one:
        return one[key]
    else:
        return float("NaN")
if __name__ == "__main__":
    datalist=fetchdata.loaddate("/root/data/golddata.gz")
    ch=ContextHost(datalist[-360:])
    ch.doLoop(run)
    print ch.marketvalue

    '''
    def DrawIndex(ax,datalist):
        poslist=[one["pos"] for one in datalist]
        disres =[getv(one,"wsvc") for one in datalist]
        ax.plot(poslist, disres , color="r")
        ax.hlines(0, poslist[0], poslist[-1], colors='b')
        ax.hlines([10, 5, 0, -5, -10], poslist[0], poslist[-1], colors=['r', 'r', 'b', 'g', 'g'], linestyles='dashdot')

    def DrawMarketValue(ax,datalist):
        poslist=[one["pos"] for one in datalist]
        disres =[getv(one,"mv") for one in datalist]
        ax.plot(poslist, disres , color="r")

    def exDrawLine(axs,datalist):
        DrawIndex(axs[1],datalist)
        DrawMarketValue(axs[2],datalist)

    show.Show(ch.data,exDrawLine,500)
    '''
